﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseAccess;
using System.Data;
using System.Text;


namespace Liguo.Administration
{
    public partial class InfoOfSales : System.Web.UI.Page
    {
        Dictionary<int , int> itemSalesAmount = new Dictionary<int,int>();//对应散件的销量
        Dictionary<int , double> disSalesAmount = new Dictionary<int,double>();//对应整件的销量
        Dictionary<int , double> moneySum = new Dictionary<int,double>(); //对应其价格
        SqlIt sql = new SqlIt();
        string startInquery;
        string endInquery;
        //double itemGoodsPrice ;
        //double disGoodsPrice ;
        //double totalPrice ;
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (IsPostBack)
            //{
            //    //TotalPrice.Visible = true;
            //    TotalPrice.Text = (Convert.ToDouble(itemPrice.Text.ToString()) + Convert.ToDouble(disPrice.Text.ToString())).ToString();
            //}
        }
        
        //指定时间段查询点击事件
        protected void ButtonInquery_Click(object sender, EventArgs e)
        {
            startInquery = startTime.Text.ToString();
            endInquery = endTime.Text.ToString();
            if (startInquery.Equals("") && endInquery.Equals(""))
            {
                Response.Write("<script>alert('请您将开始日期和结束日期添加完整！')</script>");

            }
            else if (startInquery.CompareTo(endInquery) > 0)
            {
                Response.Write("<script>alert('结束日期应在开始日期之后！')</script>");
            }
            else
            {
                displayItemGridview();
                displayDisGoodsGridview();
            }
        }
        //特定时间段查询点击事件
        protected void ButtonInqueryOther_Click(object sender, EventArgs e)
        {
            if (Radio_AllTime.Checked == true)
            {
                startInquery = "1997-01-01";
                endInquery = DateTime.Now.ToString("yyyy-MM-dd");
            }
            if (Radio_OneYear.Checked == true)
            {
                endInquery = DateTime.Now.ToString("yyyy-MM-dd");
                startInquery = dateTimeSub(endInquery, 1, 3);
                
            }
            if (Radio_OneQuarter.Checked == true)
            {
                endInquery = DateTime.Now.ToString("yyyy-MM-dd");
                startInquery = dateTimeSub(endInquery, 3, 2);
            }
            if (Radio_OneMonth.Checked == true)
            {
                endInquery = DateTime.Now.ToString("yyyy-MM-dd");
                startInquery = dateTimeSub(endInquery, 1, 2);
            }
            if (Radio_OneWeek.Checked == true)
            {
                endInquery = DateTime.Now.ToString("yyyy-MM-dd");
                startInquery = dateTimeSub(endInquery, 7, 1);
            }

            displayItemGridview();
            displayDisGoodsGridview();
        }
        

        //显示从startInquery到endInquery的销量，负责拿数据显示 
        private void displayItemGridview(){
            startTimeText.Visible = true;
            endTimeText.Visible = true;
            DataTable disGoodsTables = new DataTable("disgoodsTable");
            
            DataSet ds = sql.SpecialItem("OrderInfo", "Time between " + "'" + startInquery + "'" + " and " + "'" + endInquery + "'", "ID");
            int longth_OrderInfoID = (ds.Tables[0].Rows.Count - 1);
           
            for (int i = 0; i <= longth_OrderInfoID; i++)
            {
                int id = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"].ToString());
                DataSet ds2 = sql.SpecialItem("OrderDetail", "OrderID =" + id, "GoodsID");
                int longth_OrderGoodsListID = (ds2.Tables[0].Rows.Count - 1);
                for (int j = 0; j <= longth_OrderGoodsListID; j++)
                {
                    int goodsId = Convert.ToInt32(ds2.Tables[0].Rows[j]["GoodsID"].ToString());
                    float unitPrice = (float)Convert.ToDouble(sql.SingleSpecialItem("OrderDetail", "GoodsID =" + goodsId, "Price"));
                    int goodsType = (Int32)(sql.SingleSpecialItem("GoodsInfo", "ID =" + goodsId, "SaleMethod"));

                    if ((goodsType == 0) ||(goodsType ==1) )
                    {
                        int amount = (Int32)(sql.SingleSpecialItem("OrderDetail", "GoodsID =" + goodsId, "Amount"));
                        if (!itemSalesAmount.ContainsKey(goodsId))
                        {
                            itemSalesAmount.Add(goodsId, amount);
                            moneySum.Add(goodsId, unitPrice * amount);
                        }else
                        {
                            moneySum[goodsId] += (amount * unitPrice);
                            itemSalesAmount[goodsId] += amount;
                        }    
                    }
                    else
                    {
                        double amount = Convert.ToDouble(sql.SingleSpecialItem("OrderDetail", "GoodsID =" + goodsId, "Weight"));
                        if (!disSalesAmount.ContainsKey(goodsId))
                        {
                            disSalesAmount.Add(goodsId, amount);
                            moneySum.Add(goodsId, unitPrice * amount);
                        }
                        else
                        {
                            moneySum[goodsId] += (amount * unitPrice);
                            disSalesAmount[goodsId] += amount;
                        }
                    }
                }
            }
            
            //接下来就是显示了。整件销量和销售额，散件销量和销售额。
            //将内容建一张表
            //整件表
            double itemGoodsPrice = 0;
            DataTable itemTable = new DataTable("itemTable");
            DataColumn workCol = itemTable.Columns.Add("商品名", typeof(string));
            workCol.AllowDBNull = false;
            workCol.Unique = true;
            itemTable.Columns.Add("销量", typeof(Int32));
            itemTable.Columns.Add("销售额", typeof(float));

            DataRow workRow;
            foreach (KeyValuePair<int, int> kvp in itemSalesAmount)
            {
                string goodsName = sql.SingleSpecialItem("GoodsInfo", "ID =" + kvp.Key, "GoodsName").ToString();
                workRow = itemTable.NewRow();
                workRow[0] = goodsName;
                workRow[1] = kvp.Value;
                workRow[2] = moneySum[kvp.Key];
                itemTable.Rows.Add(workRow);
                itemGoodsPrice += moneySum[kvp.Key];
            }
            itemGridView_Anytime.DataSource = itemTable;
            itemGridView_Anytime.DataBind();
            itemPrice.Visible = true;
            if ((itemGoodsPrice - 0) != 0)
            {
                itemToP.Visible = true;
                itemPrice.Text = itemGoodsPrice.ToString("0.00");
            }
            else
            {
                itemPrice.Text = "没有售出!";
            }
        }

        private void displayDisGoodsGridview()
        {
            startTimeText.Visible = true;
            endTimeText.Visible = true;
            DataTable disGoodsTables = new DataTable("disgoodsTable");
            double disGoodsPrice = 0;
            DataSet ds = sql.SpecialItem("OrderInfo", "Time between " + "'" + startInquery + "'" + " and " + "'" + endInquery + "'", "ID");
            int longth_OrderInfoID = (ds.Tables[0].Rows.Count - 1);

            for (int i = 0; i <= longth_OrderInfoID; i++)
            {
                int id = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"].ToString());
                DataSet ds2 = sql.SpecialItem("OrderDetail", "OrderID =" + id, "GoodsID");
                int longth_OrderGoodsListID = (ds2.Tables[0].Rows.Count - 1);
                for (int j = 0; j <= longth_OrderGoodsListID; j++)
                {
                    int goodsId = Convert.ToInt32(ds2.Tables[0].Rows[j]["GoodsID"].ToString());
                    float unitPrice = (float)Convert.ToDouble(sql.SingleSpecialItem("OrderDetail", "GoodsID =" + goodsId, "Price"));
                    int goodsType = (Int32)(sql.SingleSpecialItem("GoodsInfo", "ID =" + goodsId, "SaleMethod"));

                    if ((goodsType == 0) || (goodsType == 1))
                    {
                        int amount = (Int32)(sql.SingleSpecialItem("OrderDetail", "GoodsID =" + goodsId, "Amount"));
                        if (!itemSalesAmount.ContainsKey(goodsId))
                        {
                            itemSalesAmount.Add(goodsId, amount);
                            moneySum.Add(goodsId, unitPrice * amount);
                        }
                        else
                        {
                            moneySum[goodsId] += (amount * unitPrice);
                            itemSalesAmount[goodsId] += amount;
                        }
                    }
                    else
                    {
                        double amount = Convert.ToDouble(sql.SingleSpecialItem("OrderDetail", "GoodsID =" + goodsId, "Weight"));
                        if (!disSalesAmount.ContainsKey(goodsId))
                        {
                            disSalesAmount.Add(goodsId, amount);
                            moneySum.Add(goodsId, unitPrice * amount);
                        }
                        else
                        {
                            moneySum[goodsId] += (amount * unitPrice);
                            disSalesAmount[goodsId] += amount;
                        }
                    }
                }
            }
            //散件表
            DataColumn workCol1 = disGoodsTables.Columns.Add("商品名", typeof(string));
            workCol1.AllowDBNull = false;
            workCol1.Unique = true;
            disGoodsTables.Columns.Add("销量", typeof(float));
            disGoodsTables.Columns.Add("销售额", typeof(float));

            DataRow workRow1;
            foreach (KeyValuePair<int, double> kvp in disSalesAmount)
            {
                string name = sql.SingleSpecialItem("GoodsInfo", "ID =" + kvp.Key, "GoodsName").ToString();
                workRow1 = disGoodsTables.NewRow();
                workRow1[0] = name;
                workRow1[1] = kvp.Value;
                workRow1[2] = moneySum[kvp.Key];
                disGoodsTables.Rows.Add(workRow1);
                disGoodsPrice += moneySum[kvp.Key];
            }
            disGridView_Anytime.DataSource = disGoodsTables;
            disGridView_Anytime.DataBind();
            disPrice.Visible = true;
            if ((disGoodsPrice - 0) != 0)
            {
                disToP.Visible = true;
                disPrice.Text = disGoodsPrice.ToString("0.00");
            }
            else
            {
                disPrice.Text = "没有售出!";
            }
        }

        //处理日期减法，默认types为1是减日(此时num<=当前月的日期，2减月（此时num<=12)，3减年
        private string dateTimeSub(string dateTime, int num, int types){
            string[] str1 = dateTime.Split('-');
            StringBuilder sb = new StringBuilder("");
            int currDays = Convert.ToInt32(str1[2]);
            int currMonths = Convert.ToInt32(str1[1]);
            int currYears = Convert.ToInt32(str1[0]);
            int monthsDays;
            switch ((currMonths - 1) % 12){
                case 4:
                    monthsDays = 30;
                    break;
                case 6:
                    monthsDays = 30;
                    break;
                case 9:
                    monthsDays = 30;
                    break;
                case 11:
                    monthsDays = 30;
                    break;
                case 2:
                    if((((currYears % 4) == 0) && ((currYears % 100) != 0)) || ((currYears % 400) == 0))
                        monthsDays = 29;
                    else
                        monthsDays = 28;
                    break;
                default:
                    monthsDays = 31;
                    break;
            }
            switch (types){
                case 1:
                    if(currDays <=num ){
                        if(currMonths == 1){
                            str1[0] = (currYears - 1).ToString();
                            str1[1] = "12";
                            str1[2] = (31 - (num - currDays)).ToString();
                        }else{
                            str1[1] = (currMonths - 1).ToString();
                            str1[2] = (monthsDays - (num - currDays)).ToString();
                        }
                    }else{
                        str1[2] = (currDays - num).ToString();
                    }
                    break;
                case 2:
                    if(currMonths <= num){
                        str1[0] = (currYears - 1).ToString();
                        str1[1] = (12 - (num - currMonths)).ToString();
                    }else{
                        str1[1] = (currMonths - num).ToString();
                    }
                    break;
                case 3:
                    str1[0] = (Convert.ToInt32(str1[0]) - num).ToString();
                    break;
            }
            sb.Append(str1[0]).Append("-").Append(str1[1]).Append("-").Append(str1[2]);
            return sb.ToString();
        }    
        
    }
}